<template>
	<view class="">
		<float-bar :delBtnIsShow="isShowCheck" :tabIsShowValue="100"
			:bagesCount="selectArr.length.toString()" ref="floatBar"
			@deleteData="deleteData"></float-bar>
		<view v-if="isShowCheck">
			<check-all flexdBottom :allCheck="isCheckAll" @cancelClick="cancelClick" @checkChange="checkChange"></check-all>
		</view>
	
		
		<view class="segmentedBox">
			<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" styleType="text"
				activeColor="#32DBBA"></uni-segmented-control>
			<view class="content">
				<!-- 竖屏图片 -->
				<view v-if="current === 0" class="imageBox s">
					<view class="imageItem" v-for="(item, index) in imageListS" :key="index">
						<view class="mask" @click="(e)=>maskClick(e, item)" v-if="item.isShow">
							<uni-icons :data-isdel="true" :data-fx="1" color="#fff" size="36" type="trash"></uni-icons>
						</view>
						<view class="isdel"  @longpress="longpress(item)" v-if="!item.isLoad"
							@click="goToPreviewFun($event, index, imageListH, 'image', item)"
						>
							<image src="../../static/icon/picisdel.png" mode="widthFix"></image>
							<text>壁纸不见啦!</text>
						</view>
						<image @load="imageLoad(item)" @longpress="longpress(item)" 
							@click="goToPreviewFun($event, index, imageListS, 'image', item)"
							lazy-load :src="item.url" mode="aspectFill"></image>
					</view>
				</view>
				<!-- 横屏图片 -->
				<view v-if="current === 1" class="imageBox h">
					<view class="imageItem" v-for="(item, index) in imageListH" :key="index">
						<view class="mask" @click="(e)=>maskClick(e, item)" v-if="item.isShow">
							<uni-icons :data-isdel="true" :data-fx="0" color="#fff" size="36" type="trash"></uni-icons>
						</view>
						<view  class="isdel"  @longpress="longpress(item)" v-if="!item.isLoad"
							@click="goToPreviewFun($event, index, imageListH, 'image', item)"
						>
							<image src="../../static/icon/picisdel.png" mode="aspectFit"></image>
							<text>壁纸不见啦!</text>
						</view>
						<image @load="imageLoad(item)"	@longpress="longpress(item)" 
							@click="goToPreviewFun($event, index, imageListH, 'image', item)"
							lazy-load :src="item.url" mode="aspectFill"></image>
					</view>
				</view>
				<!-- 视频 -->
				<!-- <view v-if="current === 2" class="imageBox h">
					<navigator v-for="(item, index) in videoList" :key="index" url="">
						<video @click="goToPreview($event, index, videoList, 'video')" autoplay loop muted :controls='false' object-fit='cover'
							:src="item.video_url">
						</video>
					</navigator>
				</view> -->
			</view>
		</view>

		<uni-load-more status="noMore"></uni-load-more>
		<view class="bottomBox"></view>
	</view>


</template>

<script setup>
	import {
		onLoad,
		onShow,
		onPullDownRefresh,
		onUnload,
		onReachBottom,
		onPageScroll
	} from '@dcloudio/uni-app'
	import {
		commonRequestApi
	} from '@/api/apis.js'
	import {
		ref,
		computed,
		onMounted
	} from 'vue'
	import {
		unique,
		cloudToUrlArr,
		uniqueHistory
	} from '@/utils/common.js'
	import goToPreview from '@/utils/goToPreview.js'
	
	// 分段器
	// const items = ['竖屏图片', '横屏图片', '视频壁纸']
	const items = ['竖屏壁纸', '横屏壁纸']
	const itemsTop = ['1', '2']
	const counts = ref([0, 0])
	const current = ref(0)
	// 切换分段器
	const onClickItem = (e) => {
		if (current.value != e.currentIndex) {
			current.value = e.currentIndex;
		}
		cancelClick()
	}

	// 展示的列表
	const imageListH = ref([])
	const imageListS = ref([])
	const imageList = ref([])
	const videoList = ref([])

	// 回到顶部按钮
	const tabIsShow = ref(false)
	const cacheIndex = {
		img: '',
		video: ''
	}
	let title = ''
	let isInit = false
	const init = async ()=>{
		// 提取对象中的图片cloudUrl
		let urlArr = []
		imageList.value.forEach(item => {
			if(!item.cloudUrl){
				item.cloudUrl = item.url
			}
			urlArr.push(item.cloudUrl)
		})
		
		// 区分图片横竖 、cloudUrl转url
		try{
			const res = await cloudToUrlArr(urlArr)
			// console.log(res);
			imageList.value.forEach((item, index) => {
				item.url = res[index].tempFileURL
				item.isShow = false
				if(!item.url){
					item.isLoad = false
				}
				if (item.direction == 0) {
					imageListH.value.push(item)
				} else {
					imageListS.value.push(item)
				}
			})
		}catch(e){
			console.log(e)
		}
		
		
		counts.value[0] = imageListS.value.length
		counts.value[1] = imageListH.value.length
		counts.value[2] = videoList.value.length
	}
	onShow(async () => {
		const oldlength = imageList.value.length
		// 获取缓存cacheIndex.img、cacheIndex.video
		imageList.value = uni.getStorageSync(cacheIndex.img)
		videoList.value = uni.getStorageSync(cacheIndex.video)
		const newlength = imageList.value.length
		
		// 如果是收藏且长度变化, 且不是首次进入, 重新加载数据
		if (title == '壁纸收藏' && oldlength != newlength && isInit) {
			imageListH.value = []
			imageListS.value = []
			await init()
			
		}
		// 首次进入加载数据
		if (!isInit) {
			await init()
		}
		// 已经加载过了 表示不是首次进入
		isInit = true
	})
	
	
	onLoad(async (options) => {
		uniqueHistory()
		
		cacheIndex.img = options.type + 'img'
		cacheIndex.video = options.type + 'video'
		// 设置导航栏标题
		switch (options.type) {
			case 'collectInfo_':
				title = '壁纸收藏'
				break
			case 'historyInfo_':
				title = '浏览历史'
				break
			case 'downloadInfo_':
				title = '下载记录'
				break
		}
		uni.setNavigationBarTitle({
			title: title
		})
		
	})


	const goToPreviewFun = (e, index, imageList, type, item) => {
		if(isShowCheck.value){
			// 遮罩显示
			item.isShow = true
			// 选中数组添加
			selectArr.value.push(item)
		}else{
			if(item.isLoad){
				goToPreview(e, index, imageList, type)
			}
		}
	}
	const timer = ref(null)
	// 长按
	const longpress = (item) => {
		// 多选组件显示
		isShowCheck.value = true
		// 遮罩显示
		item.isShow = true
		// 选中数组添加
		selectArr.value.push(item)
		timer.value = setTimeout(() => {
			timer.value = null
		}, 500)
		
	}
	// 遮罩点击
	const maskClick = (e, item) => {
		// console.log(e)
		// console.log(e.target.dataset.fx)
		if (e.target.dataset.isdel) {
			// console.log('点击了删除')
			// 确认是否删除
			uni.showModal({
				title: '提示',
				content: '确定删除该记录吗？',
				success: (res) => {
					if (res.confirm) {
						// 删除
						if(e.target.dataset.fx == 0){
							// console.log('删除横屏')
							imageListH.value.splice(imageListH.value.indexOf(item), 1)
						}else{
							// console.log('删除竖屏')
							imageListS.value.splice(imageListS.value.indexOf(item), 1)
						}
						imageList.value.splice(imageList.value.indexOf(item), 1)
						// counts.value[0] = imageListS.value.length
						// counts.value[1] = imageListH.value.length
						// console.log(counts.value)
						// 设置缓存
						uni.setStorageSync(cacheIndex.img, imageList.value)
						selectArr.value.splice(selectArr.value.indexOf(item), 1)
					}
				},
			})

		} else {
			// console.log('点击空白')
			if (!timer.value) {
				selectArr.value.splice(selectArr.value.indexOf(item), 1)
				item.isShow = false
			}
		}
		
	}
	// 滚动到指定位置触发 控制回到顶部按钮显隐
	onPageScroll((e) => {
		tabIsShow.value = e.scrollTop > 500
		// console.log(tabIsShow.value);

	})
	// 清除数据
	const deleteData = () => {
		uni.showModal({
			title: '提示',
			content: '确定删除所选记录吗？',
			success: (res) => {
				if (res.confirm) {
					let arr = []
					if(current.value == 0){
						// console.log('删除竖屏')
						arr = imageListS.value
					}else{
						// console.log('删除横屏')
						arr = imageListH.value
					}
					// 删除
					const selectArrCatch = [...selectArr.value]
					selectArrCatch.map(item => {
						arr.splice(arr.indexOf(item), 1)
						imageList.value.splice(imageList.value.indexOf(item), 1)
						selectArr.value.splice(selectArr.value.indexOf(item), 1)
					})
					
					uni.setStorageSync(cacheIndex.img, imageList.value)
					if(!arr.length){
						cancelClick()
					}
					// counts.value[0] = imageListS.value.length
					// counts.value[1] = imageListH.value.length
					// console.log(counts.value)
					// 设置缓存
				}
			},
		})
		
		/* 清除所有
		uni.showModal({
			title: '提示',
			content: `确定要清除所有（包括横屏和竖屏）${title}吗？`,
			success: (res) => {
				if (res.confirm) {
					uni.removeStorageSync(cacheIndex.img)
					uni.removeStorageSync(cacheIndex.video)
					videoList.value = []
					// 区分图片横竖 
					imageListH.value = []
					imageListS.value = []
					counts.value[0] = imageListS.value.length
					counts.value[1] = imageListH.value.length
					counts.value[2] = videoList.value.length

					uni.showToast({
						title: '清除成功',
						icon: 'success'
					})
				}
			}
		})
		*/
	}
	
	const imageLoad = (item) => {
		item.isLoad = true
	}
	
	// 多选组件
	const isShowCheck = ref(false)
	const selectArr = ref([])
	const isCheckAll = computed({
		get() {
			if(current.value == 0){
				// 竖屏
				return customEvery(imageListS.value)
				// imageListS.value.every(item => item.isShow)
			}else{
				// 横屏
				return customEvery(imageListH.value)
				// imageListH.value.every(item => item.isShow)
			}
		},
		set(val) {
			if(current.value == 0){
				// 竖屏
				imageListS.value.map(item => item.isShow = val)
			}else{
				// 横屏
				imageListH.value.map(item => item.isShow = val)
			}
			
		}
	})
	// every 方法
	function customEvery(arr, callback) {
	  for (let i = 0; i < arr.length; i++) {
	    if (!arr[i].isShow) {
	      return false;
	    }
	  }
	  return true;
	}
	// 全选组件 取消按钮
	const cancelClick = () => {
		isShowCheck.value = false
		isCheckAll.value = false
		selectArr.value = []
	}
	// 全选组件 全选按钮
	const checkChange = () =>{
		console.log('checkChange');
		isCheckAll.value = !isCheckAll.value
		if(current.value == 0){
			// 竖屏
			selectArr.value = imageListS.value.filter(item => item.isShow)
		}else{
			// 横屏
			selectArr.value = imageListH.value.filter(item => item.isShow)
		}
	}

	// 复选框改变
	const checkboxChange = (item) => {
		item.isShow = !item.isShow
		this.selectArr = this.$refs.udb?.dataList.filter(item => item.isShow)
		// console.log(item)
	}
	// 回到顶部
	const goTop = () => {
		uni.pageScrollTo({
			scrollTop: 0,
			duration: 300
		})
	}
</script>

<style scoped lang="scss">
	.bottomBox {
		width: 100%;
		height: 100rpx;
	}

	// .fixedBox {
	// 	position: fixed;
	// 	right: 20rpx;
	// 	bottom: 200rpx;
	// 	z-index: 110;

	// 	.fixedItem {
	// 		background-color: $theme-bg-color2;
	// 		width: 120rpx;
	// 		height: 120rpx;
	// 		border-radius: 50%;
	// 		display: flex;
	// 		justify-content: center;
	// 		/* 水平居中 */
	// 		align-items: center;
	// 		/* 垂直居中 */
	// 		box-sizing: border-box;
	// 		padding-bottom: 5rpx;
	// 		margin-bottom: 30rpx;
	// 		position: relative;
	// 		box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.2);
	// 	}

	// 	.badgeBox {
	// 		position: absolute;
	// 		bottom: 120rpx;
	// 		right: 0;

	// 	}


	// 	// 最后一个view
	// 	view:last-child {
	// 		margin-bottom: 0;
	// 	}

	// }


	.s {
		display: grid;
		grid-template-columns: repeat(2, 1fr);

		// justify-items: center;
		.imageItem {
			// 332*514
			// width: 332rpx;
			height: 514rpx;
			// padding: 10rpx;
			margin: 10rpx;
			box-sizing: border-box;

			.mask {
				width: calc(100% - 40rpx);
				height: calc(100% - 30rpx);
			}

			image {
				width: 100%;
				height: 100%;
			}
		}
	}

	.h {
		display: grid;
		grid-template-columns: repeat(1, 1fr);
		justify-items: center;

		.imageItem {
			// padding: 5rpx 10rpx;
			margin: 5rpx 10rpx;
			box-sizing: border-box;
			width: 100%;
			height: 420rpx;

			.mask {
				width: calc(100% - 40rpx);
				height: calc(100% - 20rpx);
			}

			image {
				height: 100%;
				width: 100%;
			}

			video {
				height: 100%;
				width: 100%;
			}
		}
	}

	.imageBox {
		width: 730rpx;
		margin: 0 auto;
		padding-top: 20rpx;

		.imageItem {
			position: relative;
			overflow: hidden;
			.isdel{
				:deep(){
					image{
						background-color: rgba(0,0,0,0)!important;
						width: 120rpx;
						height: 120rpx;
						margin-bottom: 20rpx;
					}
				}
				align-items: center;
				flex-direction: column;
				align-content: center;
				width: 100%;
				height: 100%;
				z-index: 9;
				display: flex;
				align-items: center;
				justify-content: center;
				position: absolute;
				background-color: rgba(240, 240, 240, 0.5);
				border-radius: 15rpx;
				font-size: 38rpx;
				color: #cccccc;
			}
			.mask {
				// padding: 5rpx 10rpx;
				width: 100%;
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
				position: absolute;
				z-index: 10;
				background-color: rgba(50, 219, 186, 0.5);
				border-radius: 15rpx;
				// 过渡
				transition: all 0.3s;

			}

			image {
				border-radius: 15rpx;
			}

			video {
				width: 100%;
				border-radius: 15rpx;
			}
		}
	}
	
	
	
	
	.afterbox {
		height: 80rpx;
	}
	.fixed {
		width: 100%;
		position: fixed;
		z-index: 90;
		background-color: #fff;
	}
	
	.isBottom {
		bottom: 0;
	}
	.topCheck {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 80rpx;
		box-sizing: border-box;
		padding: 0 30rpx 0 10rpx;
		font-size: 34rpx;
	
		.uni-label-pointer {
			display: flex;
			align-items: center;
		}
	
		text {
			color: red;
		}
	
	
	
	}
</style>